package com.szewec.ps.util.imagepicker.adapter;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import com.szewec.ps.R;
import com.szewec.ps.util.imagepicker.data.ItemType;
import com.szewec.ps.util.imagepicker.data.MediaFile;
import com.szewec.ps.util.imagepicker.manager.ConfigManager;
import com.szewec.ps.util.imagepicker.manager.SelectionManager;
import com.szewec.ps.util.imagepicker.utils.Utils;
import com.szewec.ps.util.imagepicker.view.SquareImageView;
import com.szewec.ps.util.imagepicker.view.SquareRelativeLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * 附件列表适配器（可设置查看和编辑状态——状态控制变量isShowCamera）
 */
public class CustomPickerAdapterShowAndEdit extends RecyclerView.Adapter<CustomPickerAdapterShowAndEdit.BaseHolder> {

    private List<MediaFile> mMediaFileList;
    // 删除的图片
    public boolean isShowCamera = true;
    public boolean isShowEmpty = false;
    private Context mContext;
    private String TAG  = "CustomPickerAdapterShowAndEdit";

    /*public void showEmptyIconWhenNotUseCamera(){
        if (!isShowCamera){
            isShowEmpty = true;
            notifyDataSetChanged();
        }
    }*/

    public List<MediaFile> getmMediaFileList() {
        return mMediaFileList;
    }

    public void add(MediaFile mediaFile) {
        mMediaFileList.add(mediaFile);
        notifyDataSetChanged();
    }

    public void setmMediaFileList(List<MediaFile> mMediaFileList) {
        this.mMediaFileList = mMediaFileList;
        notifyDataSetChanged();
    }

    public void AddAll(List<MediaFile> mMediaFileList){
        this.mMediaFileList.addAll(mMediaFileList);
        notifyDataSetChanged();
    }

    public void remove(int position){
        mMediaFileList.remove(position);
        notifyDataSetChanged();
    }


    public CustomPickerAdapterShowAndEdit(Context context, List<MediaFile> mediaFiles, boolean isShowCamera) {
        this.mContext = context;
        this.mMediaFileList = mediaFiles;
        this.isShowCamera = isShowCamera;
    }

    public CustomPickerAdapterShowAndEdit(Context context, List<MediaFile> mediaFiles, boolean isShowCamera, boolean isShowEmpty) {
        this.mContext = context;
        this.mMediaFileList = mediaFiles;
        this.isShowCamera = isShowCamera;
        this.isShowEmpty = isShowEmpty;
    }


    @Override
    public int getItemViewType(int position) {
        if (isShowCamera) {
            if (position == getItemCount()-1) {
                return ItemType.ITEM_TYPE_CAMERA;
            }
            //如果有相机存在，position位置需要-1
//            position--;
        }else {
            //如果不显示相机，表示是预览状态，如果需要显示数据为空，返回。
            if (isShowEmpty && mMediaFileList.size() == 0){
                return ItemType.ITEM_TYPE_EMPTY;
            }
        }
        if (mMediaFileList.get(position).getDuration() > 0) {
            return ItemType.ITEM_TYPE_VIDEO;
        } else {
            return ItemType.ITEM_TYPE_IMAGE;
        }
    }

    @Override
    public int getItemCount() {
        if (mMediaFileList == null) {
            return 0;
        }
        //如状态为查看，则不显示上传按钮
        return isShowCamera ? mMediaFileList.size() + 1 : !isShowEmpty ? mMediaFileList.size() : mMediaFileList.size()==0 ? 1 : mMediaFileList.size();
    }

    /**
     * 获取item所对应的数据源
     *
     * @param position
     * @return
     */
    public MediaFile getMediaFile(int position) {
        if (isShowCamera) {
            if (position == getItemCount()-1) {
                return null;
            }
            return mMediaFileList.get(position);
        }else {
            if (isShowEmpty && mMediaFileList.size() == 0){
                return null;
            }
        }
        return mMediaFileList.get(position);
    }


    @NonNull
    @Override
    public BaseHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        if (viewType == ItemType.ITEM_TYPE_CAMERA) {
            view = LayoutInflater.from(mContext).inflate(R.layout.item_add_photo_video, null);
            return new BaseHolder(view);
        }
        if (viewType == ItemType.ITEM_TYPE_EMPTY){
            view = LayoutInflater.from(mContext).inflate(R.layout.item_none_pic, null);
            return new BaseHolder(view);
        }
        if (viewType == ItemType.ITEM_TYPE_IMAGE) {
            view = LayoutInflater.from(mContext).inflate(R.layout.item_recyclerview_image2, null);
            return new ImageHolder(view);
        }
        if (viewType == ItemType.ITEM_TYPE_VIDEO) {
            view = LayoutInflater.from(mContext).inflate(R.layout.item_recyclerview_video2, null);
            return new VideoHolder(view);
        }
        return null;
    }


    @Override
    public void onBindViewHolder(@NonNull BaseHolder holder, final int position) {
        int itemType = getItemViewType(position);
        MediaFile mediaFile = getMediaFile(position);
        switch (itemType) {
            //图片、视频Item
            case ItemType.ITEM_TYPE_IMAGE:
            case ItemType.ITEM_TYPE_VIDEO:
                MediaHolder mediaHolder = (MediaHolder) holder;
                bindMedia(mediaHolder, mediaFile);
                break;
            //相机Item
            default:
                break;
        }
        if (itemType != ItemType.ITEM_TYPE_EMPTY){
            //设置点击事件监听
            if (mOnItemClickListener != null) {
                holder.mSquareRelativeLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mOnItemClickListener.onMediaClick(view, position);
                    }
                });

                if (holder instanceof MediaHolder) {
                    ((MediaHolder) holder).mImageCheck.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            mOnItemClickListener.onMediaCheck(view, position);
                        }
                    });
                }
            }

            //设置删除事件监听
            if(mOnDeleteClickListener !=null){
                holder.mImageDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mOnDeleteClickListener.onDeleteClick(view,position);
                    }
                });
            }
        }
    }


    /**
     * 绑定数据（图片、视频）
     *
     * @param mediaHolder
     * @param mediaFile
     */
    private void bindMedia(MediaHolder mediaHolder, MediaFile mediaFile) {
        String imagePath = mediaFile.getPath();//缩略图路径
        if (mediaFile.getId() != null && !TextUtils.isEmpty(imagePath) && imagePath.indexOf("x-oss-process") <= 0) {//id不为空代表该附件已上传到阿里云,兼容web端视频第一帧的方式
            imagePath = imagePath + "?x-oss-process=image/resize,m_fill,h_100,w_100"; //使用OSS的缩略图
        }
        //选择状态（仅是UI表现，真正数据交给SelectionManager管理）
        if (SelectionManager.getInstance().isImageSelect(imagePath)) {
            mediaHolder.mImageView.setColorFilter(Color.parseColor("#77000000"));
            mediaHolder.mImageCheck.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.icon_image_checked));
        } else {
            mediaHolder.mImageView.setColorFilter(null);
            mediaHolder.mImageCheck.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.icon_image_check));
        }

        try {
            ConfigManager.getInstance().getImageLoader().loadThumbnail(mediaFile.getType(), mediaHolder.mImageView, imagePath);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (mediaHolder instanceof ImageHolder) {
            //如果是gif图，显示gif标识
//            String suffix = imagePath.substring(imagePath.lastIndexOf(".") + 1);
//            if (suffix.toUpperCase().equals("GIF")) {
//                ((ImageHolder) mediaHolder).mImageGif.setVisibility(View.VISIBLE);
//            } else {
//                ((ImageHolder) mediaHolder).mImageGif.setVisibility(View.GONE);
//            }
        }

        if (mediaHolder instanceof VideoHolder) {
            //如果是视频，需要显示视频时长
            String duration = Utils.getVideoDuration(mediaFile.getDuration());
            ((VideoHolder) mediaHolder).mVideoDuration.setText(duration);
        }

    }

    /**
     * 图片Item
     */
    class ImageHolder extends MediaHolder {

        public ImageView mImageGif;

        public ImageHolder(View itemView) {
            super(itemView);
            mImageGif = itemView.findViewById(R.id.iv_item_gif);
        }
    }

    /**
     * 视频Item
     */
    class VideoHolder extends MediaHolder {

        private TextView mVideoDuration;

        public VideoHolder(View itemView) {
            super(itemView);
            mVideoDuration = itemView.findViewById(R.id.tv_item_videoDuration);
        }
    }

    /**
     * 媒体Item
     */
    class MediaHolder extends BaseHolder {

        public SquareImageView mImageView;
        public ImageView mImageCheck;

        public MediaHolder(View itemView) {
            super(itemView);
            mImageView = itemView.findViewById(R.id.iv_item_image);
            mImageCheck = itemView.findViewById(R.id.iv_item_check);
        }
    }

    /**
     * 基础Item
     */
    class BaseHolder extends RecyclerView.ViewHolder {

        public SquareRelativeLayout mSquareRelativeLayout;
        public ImageView mImageDelete;

        public BaseHolder(View itemView) {
            super(itemView);
            mSquareRelativeLayout = itemView.findViewById(R.id.srl_item);
            mImageDelete = itemView.findViewById(R.id.iv_item_delete);
            //如果状态为查看，则隐藏删除按钮
            if(!isShowCamera){
                mImageDelete.setVisibility(View.GONE);
            }

        }
    }


    /**
     * 接口回调，将点击事件向外抛
     */
    private OnItemClickListener mOnItemClickListener;
    private OnDeleteClickListener mOnDeleteClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.mOnItemClickListener = onItemClickListener;
    }
    public void setOnDeleteClickListener(OnDeleteClickListener onDeleteClickListener) {
        this.mOnDeleteClickListener = onDeleteClickListener;
    }

    public interface OnItemClickListener {
        void onMediaClick(View view, int position);

        void onMediaCheck(View view, int position);
    }
    public interface OnDeleteClickListener {
        void onDeleteClick(View view, int position);
    }
}
